package cn.cq.aop;

import cn.cq.annotation.OperationLogAnnotation;
import cn.cq.common.BaseUtils;
import cn.cq.common.NetUtils;
import cn.cq.admin.entity.model.TOperationLog;
import cn.cq.admin.service.TOperationLogService;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;

/**
 * cn.cq.aop
 *
 * @author  dicraft
 */
@Aspect
@Component
@Slf4j
public class OperationLogAspect {

    @Resource
    private TOperationLogService operationLogService;

    /**
     * 设置操作日志切入点   在注解的位置切入代码
     */
    @Pointcut("@annotation(cn.cq.annotation.OperationLogAnnotation)")
    public void pointCut() {

    }


    @AfterReturning(pointcut = "pointCut()",returning = "result")
    public void saveLog(JoinPoint joinPoint, Object result){
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);
        try {
            //将返回值转换成map集合
            Map<String, String> map = (Map<String, String>) result;
            TOperationLog operationLog = new TOperationLog();
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            //获取切入点所在的方法
            Method method = signature.getMethod();
            //获取操作
            OperationLogAnnotation annotation = method.getAnnotation(OperationLogAnnotation.class);
            if (annotation != null) {
                operationLog.setModule(annotation.module());
                operationLog.setType(annotation.type());
                operationLog.setDescription(annotation.description());
            }
            //操作用户
            operationLog.setUserId(StpUtil.getLoginIdAsLong());
            //操作IP
            operationLog.setIp(NetUtils.getIpAddress(request));
            //返回值信息
            operationLog.setResult(map.get("msg"));
            //保存日志
            operationLogService.save(operationLog);

        } catch (Exception e) {
            log.error(BaseUtils.getStackTrace(e));
        }
    }
}
